<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
<!--      @@@@@@@@@@@-->
      文章分类：
      <el-select v-model="q.cate_id" placeholder="请选择分类">
        <el-option
          v-for="item in articleListCategory"
          :key="item.value"
          :label="item.cate_name"
          :value="item.id">
        </el-option>
      </el-select>
      <!--      @@@@@@@@@@@-->
      文发布状态：
      <el-select v-model="q.state" placeholder="请选择文章状态">
        <el-option label="已发布" value="已发布"></el-option>
        <el-option label="草稿" value="草稿"></el-option>
      </el-select>
      <el-button type="primary" @click="filterArticleCondition">筛选</el-button>
      <el-button type="info" @click="resetFilterArticleCondition">重置</el-button>
      <el-button type="primary" class="btnSend" @click="dialogVisible = true">发表文章</el-button>
<!--      文章列表表格-->
      <el-table :data="articleList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="{ row }">
            <el-link type="primary" @click="showDetailFn(row.id)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="{ row }">
            <span>{{ $formatDate(row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="removeFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      列表分页-->
      <el-pagination
        @size-change="handleSizeChangeFn"
        @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size.sync="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
<!--      @@@@@-->
    </el-card>
<!--    发布文章dialog-->
      <el-dialog
        title="发表文章"
        :visible.sync="dialogVisible"
        width="100%"
        fullscreen
        :before-close="handleClose"
        :destroy-on-close="true"
      >
        <!--      文章发表-->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="文章标题" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="region" class="select">
            <el-select v-model="ruleForm.region" placeholder="请选择分类"  class="selectItem">
              <el-option v-for="item in articleListCategory" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容" prop="context" >
            <quill-editor v-model="content"
                          ref="myQuillEditor"
                          @blur="onEditorBlur($event)"
                          @focus="onEditorFocus($event)"
                          @ready="onEditorReady($event)">
            </quill-editor>
          </el-form-item>
          <el-form-item label="封面图片" prop="context" class="uploadImg">
            <img
              src="../../assets/images/cover.jpg"
              alt=""
              class="cover-img"
              ref="imgRef"
            />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input
              type="file"
              style="display: none"
              accept="image/*"
              ref="iptFileRef"
              @change="onCoverChangeFn"
            />
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="chooseImgFn">+ 选择封面</el-button>
          </el-form-item>
          <div class="uploadArticleBtn">
            <el-button type="primary" class="btnToSendServer" @click="uploadArticleToServer('已发布')">发布</el-button>
            <el-button type="info"    class="btnToSendServer" @click="uploadArticleToServer('草稿')">存为草稿</el-button>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer"></span>
      </el-dialog>
<!--    查看文章dialog-->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>
      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ $formatDate(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 文章的封面 -->
      <img :src="baseURLR + artDetail.cover_img" alt="" />
      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { getArticleClassification, uploadArticle, getArticleList, getArticleDetailMsg, delArticleAPI } from '@/api'
import defaultImg from '@/assets/images/cover.jpg'
import { baseURL } from '@/utils/request'

export default {
  name: 'articleList',
  data () {
    return {
      // 文章列表页数据
      articleListCategory: [],
      articleListCategoryValue: '',
      articleList: [],
      q: {
        pagenum: 1,
        pagesize: 10,
        cate_id: '',
        state: ''
      },
      total: 0,
      artDetail: [],
      detailVisible: false,
      baseURLR: baseURL,
      // 发表文章页数据
      articleState: '',
      content: '<h1>请输入文本</h1>',
      dialogVisible: false,
      imageUrl: '',
      ruleForm: {
        name: '',
        region: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择文章分类', trigger: 'blur' }
        ],
        context: [
          { required: true, message: '请输入·文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  async mounted () {
    await this.getArticleListCategory()
    await this.getArticleList()
  },
  methods: {
    // 文章列表区域
    // 筛选数据
    async getArticleListCategory () {
      const res = await getArticleClassification()
      this.articleListCategory = res.data.data
    },
    filterArticleCondition () {
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.getArticleList()
    },
    resetFilterArticleCondition () {
      this.q = {
        pagenum: 1,
        pagesize: 10,
        cate_id: '',
        state: ''
      }
      this.getArticleList()
    },
    async showDetailFn (id) {
      const { data: res } = await getArticleDetailMsg(id)
      if (res.code !== 0) return this.$message.error('获取文章详情失败!')
      this.artDetail = res.data
      // 展示对话框
      this.detailVisible = true
    },
    // 列表展示与操作
    async getArticleList () {
      const { data: res } = await getArticleList(this.q)
      this.articleList = res.data
      this.total = res.total
    },
    handleSizeChangeFn (newSize) {
      this.q.pagesize = newSize
      this.q.pagenum = 1
      this.getArticleList()
    },
    handleCurrentChangeFn (newPage) {
      // 为页码值赋值
      this.q.pagenum = newPage
      // 重新发起请求
      this.getArticleList()
    },
    async removeFn (id) {
      // 1. 询问用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 2. 取消了删除
      if (confirmResult === 'cancel') return
      // 执行删除的操作
      const { data: res } = await delArticleAPI(id)
      if (res.code !== 0) return this.$message.error('删除失败!')
      this.$message.success('删除成功!')
      // 刷新列表数据
      await this.getArticleList()
    },
    // 发表文章区域
    async handleClose (done) {
      this.$confirm('还未发布，确定要退出吗？')
        .then(_ => {
          this.$confirm('要保存在草稿箱吗？')
            .then(_ => {
              this.uploadArticleToServer('草稿')
              this.resetData()
              done()
            })
            .catch(_ => {
              this.resetData()
              done()
            })
        })
        .catch(_ => {})
    },
    resetData () {
      this.ruleForm.name = ''
      this.ruleForm.region = ''
      this.content = '<h1>请输入文本</h1>'
      this.imageUrl = ''
      this.state = ''
    },
    onEditorBlur (quill) {
    },
    onEditorFocus (quill) {
    },
    onEditorReady (quill) {
    },
    onEditorChange ({ quill, html, text }) {
      this.content = html
    },
    chooseImgFn () {
      this.$refs.iptFileRef.click()
    },
    // 封面选择改变的事件
    onCoverChangeFn (e) {
      // 获取用户选择的文件列表
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
        this.imageUrl = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      } else {
        // 用户选择了封面
        this.imageUrl = files[0]
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      }
    },
    // 发表文章请求
    async uploadArticleToServer (state) {
      const data = {
        title: this.ruleForm.name,
        cate_id: this.ruleForm.region,
        content: this.content,
        cover_img: this.imageUrl,
        state: state
      }
      const fd = new FormData()
      // 向 FormData 中追加数据
      Object.keys(data).forEach((key) => {
        fd.append(key, data[key])
      })
      const res = await uploadArticle(fd)
      if (state === '已发布') {
        if (res.data.code === 0) {
          this.$message.success(res.data.message)
          this.dialogVisible = false
          this.resetData()
        } else if (res.data.code === 2) {
          this.$message.error('有内容未填')
        }
      } else if (state === '草稿') {
        this.$message.success('已保存到草稿箱中')
        this.dialogVisible = false
        this.resetData()
      } else {
        this.$message.error('发布失败')
        this.dialogVisible = false
        this.resetData()
      }
      await this.getArticleList()
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  }
}
</script>
<style lang="less">
/*文章列表*/
.el-pagination {
  margin-top: 15px;
}
/*文章列表头部*/
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 98%;
  margin: 20px;
}

.el-select{
  margin-right: 10px;
}

.btnSend{
  position: relative;
  left: 400px;
}
/*文章列表部*/
.el-table{
  margin-top: 50px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
::v-deep .detail-box {
  img {
    width: 500px;
  }
}
/*发表文章部*/
.select{
  position: relative;
}

.selectItem{
  width: 300px;
  position: absolute;
  left: 0;
}

:deep .ql-editor{
  min-height: 300px;
}

.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.uploadImg{
  position: relative;
  right: 700px;
}

.uploadArticleBtn{
  position: relative;
  right: 650px;
}

</style>
